﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Microsoft.Xna.Framework;

namespace BattleFury.Lib.Controls
{
	public abstract class ContentControl
		: Control
	{
		private bool _childrenLoaded;
		private IEnumerable<XElement> _children;
		private object _callingObject;

		public List<IControl> Children { get; protected set; }

		protected ContentControl()
		{
			Children = new List<IControl>();
		}

		public override void Deserialize(XElement element, object callingObject)
		{
			base.Deserialize(element, callingObject);

			_children = (from c in element.Elements() select c);
			_callingObject = callingObject;
		}

		public override void Update(Microsoft.Xna.Framework.GameTime gameTime)
		{
			if (!_childrenLoaded)
			{
				foreach (var child in _children)
				{
					var name = child.Name.LocalName;
					var type = Type.GetType("BattleFury.Lib.Controls." + name);
					if (type == null) continue;
					var ctrl = (Control)Activator.CreateInstance(type);
					if (ctrl == null) continue;
					ctrl.Deserialize(child, _callingObject);
					ctrl.Skin = Skin;
					ctrl.Font = Font;
					ctrl.Position = Position + ctrl.Position;
					Children.Add(ctrl);
				}
				Children.OrderBy(x => x.GetType() == typeof(Console));
				Children.Reverse();
				_childrenLoaded = true;
			}

			for (var i = 0; i < Children.Count; i++)
			{
				var child = Children[i];
				child.Update(gameTime);
			}
		}

		public override void Draw(GameTime gameTime)
		{
			for (var i = 0; i < Children.Count; i++)
			{
				var child = Children[i];
				child.Draw(gameTime);
			}
		}
	}
}